<template>
	<view class="mayTask" :style="{ height: pageHeight }" @click="showMore = false">
		<view class="header_content" id="header_content" ref="header_content">
			<view class="header">
				<view class="header_item">
					<view class="title">筛选</view>
					<view class="btnList">
						<view :class="['btn_item', headerIndex === 5 ? 'active' : '']" @click="historyTab">
							历史待办
						</view>
						<view :class="['btn_item', headerIndex === item.id ? 'active' : '']" v-for="item in dateList"
							:key="item.id" @click="clickDateBtn(item)">
							{{ item.title }}
							<uni-icons type="arrowright" size="16" :color="item.id == headerIndex ? '#0091ff' : '#333'"
								v-if="item.id === 3"></uni-icons>
						</view>
					</view>
				</view>

				<view class="header_item">
					<view class="title">{{ headerIndex != 5 ? '日期' : '' }}</view>
					<view class="">{{ headerIndex != 5 ? dateTxt : '过往全部未完成任务' }}</view>
				</view>
			</view>
			<!-- 分类列表 -->
			<scroll-view :show-scrollbar="false" :scroll-left="scrollLeft" scroll-x="true" scroll-with-animation="true"
				:throttle="false" class="scroll-tab">
				<view class="cate" v-if="cateList.length && !offline">
					<view :class="[index == activeIndex ? 'active' : '', 'cateItem']" v-for="(item, index) in cateList"
						:key="item.status" @click="changeCate(item, index)">
						<view class="line" v-if="index === activeIndex"></view>
						{{ `${item.statusName}(${item.counts})` }}
					</view>
				</view>
			</scroll-view>

		</view>
		<scroll-view :style="{ height: scrollsettingHight }" :scroll-y="true" :refresher-enabled="isAllowRefresh"
			:refresher-triggered="triggered" @refresherpulling="onPulling" @refresherrefresh="onRefresh"
			@scroll="scroll" :scroll-top="scrollGoTop" :enhanced="true" :bounces="false">
			<view>
				<tk-screen-scroll :list="cateList" @getActIdx="getActIdx" :loading="loading" :active="activeIndex"
					:height="104" @downpull="downpull">
					<!-- <view class="offline-tips" v-if="offline">
						<image src="@/static/images/reload.png"> </image>
						当前网络离线，下拉刷新列表
					</view> -->
					<view class="status-tabs" v-if="headerIndex == 5">
						<view class="tab-item" v-if="typeStatus == 1" :class="{ active: activeTab == 0 }"
							@click="switchTab(0)">
							全部
						</view>
						<view class="tab-item" v-if="typeStatus == 1" :class="{ active: activeTab == 1 }"
							@click="switchTab(1)">
							年审梯
						</view>
						<view class="tab-item" v-if="typeStatus == 1" :class="{ active: activeTab == 2 }"
							@click="switchTab(2)">
							非年审梯
						</view>
						<view class="sort-item" @click="changeSort">
							<text :class="sort > 0 ? 'sort-act' : ''">排序</text>
							<image class="icon" v-if="sort == 0" src="@/static/images/sort_0.png"> </image>
							<image class="icon" v-if="sort == 1" src="@/static/images/sort_1.png"> </image>
							<image class="icon" v-if="sort == 2" src="@/static/images/sort_2.png"> </image>
						</view>
					</view>
					<view class="main">

						<view class="card" v-if="disFinishlist && disFinishlist.length">
							<!-- 小区 -->
							<view v-for="(item, index) in disFinishlist" :key="index">
								<card :rescue="item.rescue" :date="{ ...item, finish: false }" @update="loadData"
									:finish="false" :popupShow="popupShow" @petName="petName"></card>
							</view>

							<!-- 小区end -->
						</view>
						<!-- 已完成 -->
						<view class="card grey" v-if="finishList.length">
							<card :date="{ maintainPlanContentListVos: finishList, finish: true }" :finish="true">
							</card>

							<!-- 小区end -->
						</view>
						<view class="more" v-if="!loading && isLoadMore">- 已经到底了 -</view>
						<view class="more" v-if="!loading && !isLoadMore">- 上拉加载更多 -</view>
						<view class="more" v-if="loading">加载中..</view>
						<view class="finishCard" v-if="disFinishlist.length || finishCounts > 0"></view>
						<!-- 已完成end -->
						<!-- 暂无计划 -->
						<view class="empty" v-if="!finishList.length && !disFinishlist.length">
							<image
								src="https://erised-fresh.oss-cn-shenzhen.aliyuncs.com/592800/1753922096215_rkdkf67i.png"
								mode=""></image>
							<view>暂无数据</view>
						</view>
						
					</view>
				</tk-screen-scroll>
			</view>
		</scroll-view>
		<!-- 点定义选择时间 -->

		<time-select :beforeToday="true" :atterToday="true" v-if="selectTimePopup"
			@close="closeSelectTimePopup"></time-select>

		<view-top ref="viewTop" :scrollTop="scrollTop" @goTop="goTop"></view-top>
		<!-- 作业中浮窗 -->
		<movable-area class="movable-area" v-if="showFloat.show">
			<movable-view class="movable-view" :x="x" :y="y" direction="vertical">
				<view class="workingFloat" id="workingFloat"
					:style="showMore ? 'border-radius: 16px 0px 0px 16px;' : ''">
					<view class="content" @click.stop="workingFloat">
						<image src="/static/images/working.png" mode=""></image>
						<view class="word">作业中</view>
						<uni-icons v-if="showFloat.more" :type="showMore ? 'arrowup' : 'arrowdown'" size="16"
							color="#999;"></uni-icons>
					</view>
					<block v-if="showMore">
						<view v-for="(item, index) in workListPlus" :key="index" class="moreItem"
							@click.stop="accurateWorking(item, index)">
							{{ item.name }}
						</view>
					</block>
				</view>
			</movable-view>
		</movable-area>
		<!-- 项目别名 -->
		<aliasPopup :showAlias="popupShow" :aliasArr="aliasArr" @closedMask="closedMask"></aliasPopup>
		<aiCustomer v-if="findRoute('Airobot')"></aiCustomer>
	</view>
</template>

<script>
import {
	getNowTime,
	formatTime,
	getWeekDate,
	getMonthDate,
} from '@/utils/utils.js';
import { mapState } from 'vuex';
import {
	getRescueOrders,
	getWorking,
	statistics,
	getList,
	getFinshList,
} from '@/apis/index.js';
import aiCustomer from '../components/ai-customer/ai-customer.vue';
import card from '@/pages/index/components/card.vue';
import timeSelect from '@/pages/index/components/timeSelect.vue';
// import TabBar from '../home/components/tab-bar/index.vue'
import TkScreenScroll from '@/components/tk-screen-scroll/index';
import viewTop from '@/components/viewTop/viewTop.vue';
import aliasPopup from '@/components/card-dial/aliasPopup.vue';
import { mergeList } from '@/utils/utils.js';
import dayjs from 'dayjs';
export default {
	components: {
		card,
		timeSelect,
		TkScreenScroll,
		viewTop,
		aliasPopup,
		aiCustomer
	},
	data() {
		return {
			overflowShow: false,
			pageHeight: '0px',
			// 浮窗x坐标
			x: 0,
			// 浮窗y坐标
			y: 0,
			// 作业中工单浮窗展开判断
			showMore: false,
			// 作业中工单
			workingList: [],
			// 返回顶部
			scrollGoTop: 0,
			// 滚动距离
			scrollTop: 0,
			scrollsettingHight: 0,
			isAllowRefresh: true,
			triggered: false,

			// tabList:[]
			map: {
				0: { start: new Date(), end: new Date() },
				1: { start: getWeekDate().startDate, end: getWeekDate().endDate },
				2: { start: getMonthDate().startDate, end: getMonthDate().endDate },
				5: { start: dayjs().subtract(2, 'year').format('YYYY-MM-DD'), end: dayjs().format('YYYY-MM-DD') }
			},
			dateTxt: getNowTime().replace(/-/g, '/'),

			// 历史待办年审状态 1年审 2非 0全部
			activeTab: 0,
			sort: 0,
			// 日期筛选
			headerIndex: 0,
			oldHeaderIndex: 0,
			// 分类tab
			activeIndex: 0,
			// 分类列表
			cateList: [],
			// 进行中列表
			disFinishlist: [],
			// 完成列表
			finishList: [],
			finishCounts: 0,
			// 默认分类全部
			typeStatus: '',
			selectTimePopup: false,
			// 自定义日期开始时间
			beginTime: '',
			// 自定义日期结束时间
			endTime: '',
			popupShow: false,
			// 项目别名数组
			aliasArr: [],
			latitude: '',
			longitude: '',
			loading: false,
			// 分类的滑动距离
			scrollLeft: 0,
			// 分类每个item的宽度
			itemWidth: 0,
			totalWidth: 10000,
			// defaultTypeStatus: "", //获取模版消息跳进来的去到哪个类型工单
			workList: [
				{ id: 1, name: '保养作业中' },
				{ id: 2, name: '维修作业中' },
				// {id:3,name:"救援作业中"},
				{ id: 4, name: '配件作业中' },
				{ id: 5, name: '事务作业中' },
				{ id: 6, name: '质检作业中' },
				{ id: 9, name: '整改作业中' },
			],
			workListPlus: [],
			size: 3,
			current: 1,
			total: 0,
			isLoadMore: false,
			// 救援列表
			rescueList: [],
			timers: null,
		};
	},
	computed: {
		...mapState('user', ['userinfo']),
		...mapState('system', ['onlineStatus']),// 离线状态 ture 在线
		offline() {
			return !this.onlineStatus;
		},
		showFloat() {
			let amount = 0;
			for (let index = 0; index < this.workingList.length; index++) {
				// planType!=3 排除救援任务
				if (
					this.workingList[index].planCounts &&
					this.workingList[index].planType != 3
				) {
					amount++;
				}
			}
			if (amount == 1) return { show: true, more: false };
			else if (amount > 1) return { show: true, more: true };
			else return { show: false, more: false };
		},
		dateList() {
			if (this.offline) {
				return [{ title: '今日', id: 0 }];
			} else {
				return [
					{ title: '今日', id: 0 },
					{ title: '本周', id: 1 },
					{ title: '本月', id: 2 },
					{ title: '自定义', id: 3 },
				];
			}
		},
	},
	destroyed() {
		this.closeTimer();
		uni.$emit('myTaskHide');
	},
	watch: {
		onlineStatus(val) {
			if (val) {
				this.getLocationFun();
			}
		}

	},
	mounted() {
		let config = uni.getSystemInfoSync();
		// 84是拖拽盒子宽度
		this.x = config.screenWidth - 84;
		this.y = config.windowHeight - 260;
		this.pageHeight = config.windowHeight - 60 + 'px';
		// 计算每个分类item的宽度
		wx.createSelectorQuery()
			.in(this)
			.select('.header_content')
			.boundingClientRect((rect) => {
				this.scrollsettingHight = config.windowHeight - 60 - rect.height + 'px';
				console.log(rect, this.scrollsettingHight, 'rect1');

				this.$forceUpdate();
			})
			.exec();

		console.log('this.x', this.x);
	},
	methods: {

		// 获取顶部分类统计
		getCate() {
			if (this.offline) {
				return;
			}
			console.log('分类接口');
			const params = {
				typeStatus: this.typeStatus,
				latitude: this.latitude,
				longitude: this.longitude,
			};
			// 自定义时间
			if (this.headerIndex == 3) {
				params.beginTime = this.beginTime + ' 00:00:00';
				params.endTime = this.endTime + ' 23:59:59';
			} else {
				params.beginTime =
					formatTime(this.map[this.headerIndex.toString()].start) + ' 00:00:00';
				params.endTime =
					formatTime(this.map[this.headerIndex.toString()].end) + ' 23:59:59';
			}

			if (this.headerIndex == 5) {
				// 历史待办
				params.searchHistory = true;
			}
			const randomFuc = () => {
				return Math.floor(Math.random() * (1000 - 1 + 1)) + 1;
			};

			statistics(params).then((res) => {
				console.log(res, '获取分类');
				let cateList = res.data || [];

				let counts = 0;
				cateList.forEach((item) => {
					counts += item.counts;
				});
				counts = counts - cateList.find((e) => e.statusName == '已完成').counts;
				cateList.unshift({
					counts,
					statusName: '全部',
					status: '',
					key: randomFuc(),
				});
				if (this.headerIndex == 5) {
					this.cateList = cateList.filter(item => {
						return item.statusName != '已完成';
					});
				} else {
					this.cateList = cateList;
				}
			});
		},
		// 工作中浮窗 展开点击
		accurateWorking(obj) {
			let item = obj.planDetailVos[0] || {};
			let overdueName;
			let planCheckName;
			switch (obj.id) {
			case 1:
				overdueName = item.overdueName;
				planCheckName = item.planCheckName;
				uni.navigateTo({
					url: `/subpages/workOrders/detail?planId=${item.planId}&elevatorId=${item.elevatorId}&overdueName=${overdueName}&planCheckName=${planCheckName}`,
				});
				break;
			case 2:
				uni.navigateTo({
					url: `/subpages/repair/repariDetail?planId=${item.planId}&elevatorId=${item.elevatorId}`,
				});
				break;
			case 4:
				uni.navigateTo({
					url: `/subpages/workOrders/partOrder?planId=${item.planId}&elevatorId=${item.elevatorId}`,
				});
				break;
			case 5:
				uni.navigateTo({
					url: `/subpages/repair/affair/affairDetail?planId=${item.planId}&elevatorId=${item.elevatorId}`,
				});
				break;
			case 6:
				uni.navigateTo({
					url: `/subpages/quality/qualityDetail?planId=${item.planId}&elevatorId=${item.elevatorId}`,
				});
				break;
			case 9:
				uni.navigateTo({
					url: `/subpages/correction/detail?planId=${item.planId}&elevatorId=${item.elevatorId}`,
				});
				break;
			}
		},
		// 工作中浮窗 浮窗点击
		workingFloat() {
			// 多作业 展开
			if (this.showFloat.more) {
				this.showMore = !this.showMore;
				this.$nextTick(() => {
					// 展开超出边界 反弹
					let config = uni.getSystemInfoSync();
					const query = uni.createSelectorQuery().in(this);
					query
						.select('#workingFloat')
						.boundingClientRect((data) => {
							if (data.top >= config.windowHeight - data.height) {
								this.y = 0;
								this.$nextTick(() => {
									this.y = config.windowHeight - data.height;
								});
							}
						})
						.exec();
				});
				return;
			}
			// 单作业 跳转
			this.workingList.forEach((e) => {
				if (e.planCounts && e.planType == 1) {
					// let objs = {
					// 	overdueName: e.planDetailVos[0].overdueName,
					// 	planCheckName: e.planDetailVos[0].planCheckName
					// }
					let overdueName = e.planDetailVos[0].overdueName;
					let planCheckName = e.planDetailVos[0].planCheckName;
					uni.navigateTo({
						url: `/subpages/workOrders/detail?planId=${e.planDetailVos[0].planId}&elevatorId=${e.planDetailVos[0].elevatorId}&overdueName=${overdueName}&planCheckName=${planCheckName}`,
					});
				} else if (e.planCounts && e.planType == 2) {
					uni.navigateTo({
						url: `/subpages/repair/repariDetail?planId=${e.planDetailVos[0].planId}&elevatorId=${e.planDetailVos[0].elevatorId}`,
					});
				} else if (e.planCounts && e.planType == 4) {
					uni.navigateTo({
						url: `/subpages/workOrders/partOrder?planId=${e.planDetailVos[0].planId}&elevatorId=${e.planDetailVos[0].elevatorId}`,
					});
				} else if (e.planCounts && e.planType == 5) {
					uni.navigateTo({
						url: `/subpages/repair/affair/affairDetail?planId=${e.planDetailVos[0].planId}&elevatorId=${e.planDetailVos[0].elevatorId}`,
					});
				} else if (e.planCounts && e.planType == 6) {
					uni.navigateTo({
						url: `/subpages/quality/qualityDetail?planId=${e.planDetailVos[0].planId}&elevatorId=${e.planDetailVos[0].elevatorId}`,
					});
				} else if (e.planCounts && e.planType == 9) {
					uni.navigateTo({
						url: `/subpages/correction/detail?planId=${e.planDetailVos[0].planId}&elevatorId=${e.planDetailVos[0].elevatorId}`,
					});
				}
			});
		},
		goTop() {
			this.scrollGoTop = 1;
			this.$nextTick(() => {
				this.scrollGoTop = 0;
			});
		},
		scroll(e) {
			this.showMore = false;
			this.scrollTop = e.target.scrollTop;
			if (e.target.scrollTop > 100) {
				this.isAllowRefresh = false;
			} else {
				this.isAllowRefresh = true;
			}
		},
		// 下拉控件触发
		onPulling() {
			// console.log('555');
			this.triggered = true;
			setTimeout(() => {
				this.triggered = false;
			}, 500);
		},
		// 下拉触发
		onRefresh() {
			console.log('下拉出发000');
			this.triggered = true;
			this.current = 1;
			this.disFinishlist = [];
			this.getTaskList();
		},
		// 组件内下拉 触底
		downpull() {
			console.log('下拉出发1111', this.isLoadMore);
			if (!this.isLoadMore) { // isLoadMore=true 最大页数无需再加载
				// 此处判断，上锁，防止重复请求

				this.current += 1;
				this.getTaskList();
			}
		},
		getActIdx(res) {
			this.showMore = false;
			this.activeIndex = res;
			this.typeStatus = this.cateList[this.activeIndex].status;
			this.current = 1;
			this.disFinishlist = [];
			this.finishList = [];
			if (this.typeStatus == 10) {
				//   这里调已完成的接口
				// this.getFinshList();
				console.log(this.beginTime, this.endTime);
				const params = {
					typeStatus: this.typeStatus,
					latitude: this.latitude,
					longitude: this.longitude,
				};
				// 自定义时间
				if (this.headerIndex == 3) {
					params.beginTime = this.beginTime + ' 00:00:00';
					params.endTime = this.endTime + ' 23:59:59';
				} else {
					params.beginTime =
						formatTime(this.map[this.headerIndex.toString()].start) +
						' 00:00:00';
					params.endTime =
						formatTime(this.map[this.headerIndex.toString()].end) + ' 23:59:59';
				}
				this.getFinshList(params);
			} else {
				this.loadData();
			}
			this.goTop();

			if (this.typeStatus !== 2 && this.typeStatus) {
				this.closeTimer();
				// 关闭子组件定时器
				uni.$emit('myTaskHide');
			}
			if (this.typeStatus === 2 || !this.typeStatus) {
				this.initTimer();
			}
		},

		// 获取列表数据
		async getTaskList(data) {
			if (this.typeStatus == 10) {
				const params = {
					typeStatus: this.typeStatus,
					latitude: this.latitude,
					longitude: this.longitude,
				};
				// 自定义时间
				if (this.headerIndex == 3) {
					params.beginTime = this.beginTime + ' 00:00:00';
					params.endTime = this.endTime + ' 23:59:59';
				} else {
					params.beginTime =
						formatTime(this.map[this.headerIndex.toString()].start) +
						' 00:00:00';
					params.endTime =
						formatTime(this.map[this.headerIndex.toString()].end) + ' 23:59:59';
				}
				this.getFinshList(params);
				return;
			}
			console.log('getTaskList', data);
			if (this.isLoadMore && this.disFinishlist.length && !(this.typeStatus == 3 || this.typeStatus == '')) {
				return;
			}
			this.isLoadMore = true;
			// if (this.loading || this.isLoadMore) {
			// 	return;
			// }

			uni.showLoading({
				title: '加载中',
				mask: true,
			});
			this.loading = true;
			const params = {
				typeStatus: this.typeStatus,
				latitude: this.latitude,
				longitude: this.longitude,
				current: this.current,
				size: this.size,
			};
			// 自定义时间
			if (this.headerIndex == 3) {
				params.beginTime = this.beginTime + ' 00:00:00';
				params.endTime = this.endTime + ' 23:59:59';
			} else {
				params.beginTime =
					formatTime(this.map[this.headerIndex.toString()].start) + ' 00:00:00';
				params.endTime =
					formatTime(this.map[this.headerIndex.toString()].end) + ' 23:59:59';
			}
			if (this.headerIndex == 5) {
				// 历史待办
				params.searchHistory = true;
				if (this.sort == 2) {
					params.sortByPlanDateASC = true;
				}
				if (this.typeStatus == 1 && this.activeTab > 0) {
					params.useType = ['', '0', 1][this.activeTab];
				}
				console.log(this.sort, this.activeTab, params, { ...params });
			}

			if (this.offline) {
				this.getLocalLists();

				return;
			}
			this.getWorking();

			// console.log(this.headerIndex, this.beginTime, this.endTime, params)
			return new Promise((resove) => {
				getList({ ...params })
					.then(async (res) => {
						// 如果救援
						if (this.typeStatus == 3 || this.typeStatus == '') {
							let rescue = (await this.getRescueOrders()) || [];
							if (this.typeStatus == 3) {
								this.disFinishlist = rescue;
							} else {
								this.disFinishlist = mergeList(this.disFinishlist, res.data.records, 'planDate');
								if (this.current == 1) {
									this.disFinishlist.unshift(...rescue);
								}
							}
							console.log(6666, this.typeStatus, this.current, this.disFinishlist);
						} else {
							console.log('#getTaskList：this.disFinishlist = this.disFinishlist.concat(res.data.records); this.disFinishlist.length：', this.disFinishlist.length);
							this.disFinishlist = mergeList(this.disFinishlist, res.data.records, 'planDate');
							this.total = res.data.total;
						}

						if (res.data.records.length < this.size) {
							// 已加载完全部
							this.isLoadMore = true;
						} else {
							this.isLoadMore = false;
						}
						this.loading = false;
						resove();
						uni.hideLoading();
					})
					.catch(() => {
						this.loading = false;
						uni.hideLoading();
					});
			});
		},

		// 获取本地列表（离线
		getLocalLists() {
			const resetData = async (res) => {
				console.log('resetData', res);
				// 取消下拉刷新状态
				this.triggered = false;
				try {
					let { total, records, pages } = res;
					// let rescue = [];
					if (!records) {
						records = [];
					}
					this.disFinishlist = records;
					// this.loading = false;
				} catch (error) {
					console.log(error, 'error');
				}
				this.$nextTick(() => {
					uni.hideLoading();
				});
			};
			// 重置tab栏
			this.activeIndex = 0;
			uni.getStorage({
				key: 'offline_orders',
				success: (res) => {
					resetData({ ...res.data, offline: true });
				},
				fail: () => {
					resetData({});
				},
			});
		},
		// 获取作业中的数据
		getWorking() {
			getWorking().then((res) => {
				let arr = res.data || [];
				this.workListPlus = [];
				arr.forEach((item) => {
					this.workList.forEach((pro) => {
						if (item.planType === pro.id) {
							this.workListPlus.push({ ...item, ...pro });
						}
					});
				});
				this.workingList = arr;
			});
		},

		// 获取位置
		getLocationFun(data) {
			console.log('getLocationFun', this.offline, getApp().globalData.localinfo);
			this.current = 1;
			this.disFinishlist = [];
			this.finishList = [];
			if (this.offline) {
				this.getLocalLists();
				return;
			}
			return new Promise((resolve) => {
				// #ifdef MP-WEIXIN
				if (getApp().globalData.localinfo.latitude) {
					if (
						new Date().getTime() - getApp().globalData.localinfo.time <=
						1000 * 60 * 2
					) {
						this.latitude = getApp().globalData.localinfo.latitude;
						this.longitude = getApp().globalData.localinfo.longitude;
						this.getTaskList(data);
						this.getCate();
						resolve(true);
						return;
					}
				}
				// #endif

				// #ifdef H5
				this.getTaskList(data);
				this.getCate();
				resolve(false);
				// #endif

				// #ifdef MP-WEIXIN
				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						console.log('getLocation-suc');
						this.latitude = res.latitude;
						this.longitude = res.longitude;
						getApp().globalData.localinfo = {
							...res,
							time: new Date().getTime(),
						};
						this.getTaskList(data);
						this.getCate();
						resolve(true);
					},
					fail: (err) => {
						console.log('getLocation-fail', err);
						uni.showModal({
							title: '提示',
							content: '检测到尚未开启位置，请手动开启定位设置',
							success: (res) => {
								if (res.confirm) {
									wx.openSetting({
										success: (res) => {
											if (res.authSetting['scope.userLocation']) {
												wx.getLocation({
													type: 'gcj02',
													success: (data) => {
														this.latitude = data.latitude;
														this.longitude = data.longitude;
													},
												});
											}
										},
									});
								}
							},
						});
						this.getTaskList(data);
						this.getCate();
						resolve(false);
					},
				});
				// #endif
			});
		},

		// 点击分类按钮
		changeCate(item, index) {
			console.log(item, index, this.cateList, 'cate');
			// this.scrollLeft=0
			wx.createSelectorQuery()
				.in(this)
				.select('.cateItem')
				.boundingClientRect((data) => {
					this.itemWidth = data.width + 20;
					// 添加滚距离
					if (index < 2) {
						this.scrollLeft = 0;
					} else if (index > 4) {
						this.scrollLeft = this.itemWidth * (index + 1) + 40;
					} else {
						this.scrollLeft = this.itemWidth * (index + 1);
					}
					console.log(this.scrollLeft, 'scrollLeft');
				})
				.exec();
			this.activeIndex = index;
			this.current = 1;
			this.typeStatus = item.status;
			this.finishList = [];
			this.disFinishlist = [];
			if (item.status == 10) {
				//   这里调已完成的接口
				// this.getFinshList();
				console.log(this.beginTime, this.endTime);
				const params = {
					typeStatus: this.typeStatus,
					latitude: this.latitude,
					longitude: this.longitude,
				};
				// 自定义时间
				if (this.headerIndex == 3) {
					params.beginTime = this.beginTime + ' 00:00:00';
					params.endTime = this.endTime + ' 23:59:59';
				} else {
					params.beginTime =
						formatTime(this.map[this.headerIndex.toString()].start) +
						' 00:00:00';
					params.endTime =
						formatTime(this.map[this.headerIndex.toString()].end) + ' 23:59:59';
				}
				this.getFinshList(params);
			} else {
				this.loadData();
			}

			this.goTop();

			if (this.typeStatus != 2 && this.typeStatus) {
				this.closeTimer();
				// 关闭维修子组件定时器
				uni.$emit('myTaskHide');
			}
			if (this.typeStatus === 2 || !this.typeStatus) {
				this.initTimer();
			}
		},
		getFinshList(params) {
			console.log('getFinshList', new Date().getTime());
			getFinshList(params).then((res) => {
				console.log(res, '已完成');
				if (res.data) {
					this.disFinishlist = [];
					this.finishList = res.data;
				}
			});
		},
		// 加载首页数据
		async loadData() {
			this.getCate();
			// console.log('this.cate');
			await this.getTaskList();
		},

		switchTab(tab) {
			this.activeTab = tab;
			this.current = 1;
			this.disFinishlist = [];
			this.loadData();
		},
		changeSort() {
			this.sort = [2, 0, 1][this.sort];
			this.current = 1;
			this.disFinishlist = [];
			this.loadData();
		},
		historyTab() {
			this.loading = true;
			this.headerIndex = 5;
			this.activeIndex = 0;
			this.goTop();
			this.current = 1;
			this.typeStatus = '';
			let startDay = dayjs().subtract(2, 'year').format('YYYY-MM-DD HH:mm:ss');
			let endDay = dayjs().format('YYYY-MM-DD HH:mm:ss');
			this.dateTxt = startDay + '-' + endDay;
			this.loadData();
			this.scrollLeft = 0;
			return;
		},
		// 点击日期筛选
		clickDateBtn(item) {
			console.log('点击日期筛选');
			this.goTop();
			this.current = 1;
			this.disFinishlist = [];
			this.typeStatus = '';
			if (item.id == 0 || item.id == 3) {
				if (item.id == 0) {
					this.dateTxt = getNowTime().replace(/-/g, '/');
					this.headerIndex = item.id;
					this.activeIndex = 0;
					this.loadData();
				} else {
					this.selectTimePopup = true;
					this.oldHeaderIndex = this.headerIndex;
				}
			} else {
				console.log('这里是自定义数据');
				this.headerIndex = item.id;
				this.activeIndex = 0;
				let startDay = formatTime(this.map[item.id.toString()].start, '/');
				let endDay = formatTime(this.map[item.id.toString()].end, '/');
				this.dateTxt = startDay + '-' + endDay;
				this.finishList = [];
				this.disFinishlist = [];
				this.loadData();
				this.scrollLeft = 0;
			}
		},
		closeSelectTimePopup(val) {
			// 如果选择了日期
			if (val) {
				this.headerIndex = 3;

				// 如果选择了时间范围
				if (val.includes('-')) {
					let ary = val.split('-');
					let start = ary[0].replaceAll('.', '-');
					let end = ary[1].replaceAll('.', '-');
					this.beginTime = start;
					this.endTime = end;
					this.dateTxt =
						start.replaceAll('-', '/') + '-' + end.replaceAll('-', '/');
					this.filterTime(start, end);
				} else {
					// 如果选了单个日期
					const time = val.replaceAll('.', '-');
					this.beginTime = time;
					this.endTime = time;
					this.dateTxt = time.replaceAll('-', '/');
					this.filterTime(this.beginTime, this.endTime);
				}
			} else {
				// 日期取消操作
				console.log('点击了自定义日期取消');
				this.headerIndex = this.oldHeaderIndex;
				console.log(this.oldHeaderIndex, '旧的');
				console.log(this.headerIndex);
			}
			this.selectTimePopup = false;
		},

		// 获取进行中救援工单
		getRescueOrders() {
			return new Promise((resove) => {
				const params = {
					userId: this.userinfo.user_id,
					latitude: this.latitude,
					longitude: this.longitude
				};
				// 自定义时间
				if (this.headerIndex == 3) {
					params.startDate = this.beginTime + ' 00:00:00';
					params.endDate = this.endTime + ' 23:59:59';
				} else {
					params.startDate =
						formatTime(this.map[this.headerIndex.toString()].start) + ' 00:00:00';
					params.endDate =
						formatTime(this.map[this.headerIndex.toString()].end) + ' 23:59:59';
				}

				if (this.headerIndex == 5) { 
					if (this.sort == 2) {
						params.sortByPlanDateASC = true;
					}  
				}
				getRescueOrders(params)
					.then((res) => {
						let num = 0;

						let list = res.data || [];
						for (let i = 0; i < list.length; i++) {
							num = num + list[i].list.length;
							for (let j = 0; j < list[i].list.length; j++) {
								list[i].list[j].typeStatus = 3;
								if (list[i].list[j].planContentUsers) {
									list[i].list[j].planContentUsers.forEach((item) => {
										if (item.signUser) {
											item.isPlanStatus = item.signUser.isPlanStatus;
											item.isTakePartIn = item.signUser.isTakePartIn;
										}
									});
								}
								list[i].list[j].signUsers =
									list[i].list[j].planContentUsers || [];
							}
						}
						let arr = [];
						if (list.length) {
							arr.push({
								rescue: true,
								maintainPlanContentListVos: list,
								planDate: this.headerIndex == 5 ? '救援任务' : (getNowTime() + '(' + num + ')'),
								num,
							});
						}
						resove(arr);
					})
					.catch(() => {
						resove();
					});
			});
		},
		async filterTime() {
			this.getTaskList();
			this.getCate();
		},

		petName(obj) {
			this.popupShow = true;
			this.aliasArr = (obj.aliasStr || '').split(',');
			// eslint-disable-next-line vue/custom-event-name-casing
			this.$emit('overShow', true);
		},
		closedMask() {
			this.popupShow = false;
			// eslint-disable-next-line vue/custom-event-name-casing
			this.$emit('overShow', false);
		},

		// 维修工单定时器2分钟执行一次
		initTimer() {
			if (this.timers) {
				clearInterval(this.timers);
			}
			if (this.typeStatus === 2 || !this.typeStatus) {
				this.timers = setInterval(() => {
					this.current = 1;
					this.finishList = [];
					this.disFinishlist = [];
					this.loadData();
				}, 2 * 60 * 1000);
			}
		},
		// 关闭定时器
		closeTimer() {
			if (this.timers) {
				clearInterval(this.timers);
			}
		},

	},
};
</script>

<style lang="scss" scoped>
scroll-view ::-webkit-scrollbar {
	display: none;
	width: 0;
	height: 0;
	color: transparent;
}

$all_width: 96rpx;
$all_height: 96rpx;

.movable-area {
	height: 100vh;
	width: 750rpx;
	top: 0;
	left: 0;
	position: fixed;
	z-index: 300;
	pointer-events: none; //此处要加，鼠标事件可以渗透

	.movable-view {
		width: $all_width;
		height: $all_height;
		pointer-events: auto; //恢复鼠标事件

		image {
			width: $all_width;
			height: $all_height;
		}
	}
}

.mayTask {
	min-height: calc(100vh - 50px);
	background-color: #f3f6f8;

	.header {
		padding: 0rpx 20rpx;
		padding-bottom: 12rpx;
		background-color: #2c2c2c;

		.header_item {
			display: flex;
			font-size: 24rpx;
			color: #fff;

			align-items: center;

			.title {
				font-size: 26rpx;
				width: 80rpx;
				text-align: left;
			}

			.btnList {
				display: flex;
				height: 68rpx;
				align-items: center;

				.btn_item {
					background: #ddd;
					border-radius: 8rpx;
					color: #333;
					font-size: 24rpx;
					padding: 6rpx 20rpx;
					margin-right: 16rpx;
				}

				.active {
					color: #0091ff;
					background-color: #fff;
					font-weight: 600;
				}
			}
		}
	}

	.scroll-tab {
		background-color: #fff;
		white-space: nowrap;
		/* 必要，导航栏才能横向*/
		text-align: center;
		border-bottom: 2rpx solid #eee;
	}

	.cate {
		display: flex;
		height: 88rpx;
		padding: 0 20rpx;
		background-color: #fff;
		color: #93b1c7;
		font-size: 26rpx;
		width: 100%;
		overflow: auto;
		min-width: 800rpx;

		.cateItem {
			display: flex;
			align-items: center;
			margin: 0 16rpx;
			height: 100%;
			position: relative;

			.line {
				width: 100%;
				height: 4rpx;
				background-color: #0091ff;
				position: absolute;
				bottom: 0;
				left: 0;
				border-radius: 4rpx;
			}
		}

		.cateItem:nth-child(1) {
			margin-left: 0;
		}

		.active {
			font-weight: 500;
			font-size: 30rpx;
			color: #0091ff;
		}
	}

	.card {
		margin: 0 auto;
		// margin-top: 16rpx;
		width: calc(100% - 40rpx);
		border-radius: 8rpx;
		overflow: initial !important;
		overflow-x: hidden;

		&-head {
			height: 72rpx;
			display: flex;
			justify-content: flex-end;
			align-items: center;
			width: 100%;
			position: relative;
			background-color: #ebebeb;

			&-title {
				display: flex;
				align-items: center;
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
				position: absolute;
				left: 20rpx;
				font-size: 28rpx;
				height: 72rpx;

				image {
					width: 48rpx;
					height: 48rpx;
					margin-right: 10rpx;
				}
			}

			.bg {
				width: 356rpx;
				height: 96rpx;
			}
		}
	}

	.grey {
		background-color: #f3f6f8;

		.content {
			background-color: #ebebeb !important;
		}
	}

	.finishCard {
		width: 100%;
		height: 150px;
	}

	.empty {
		padding-top: 120rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		font-size: 28rpx;
		color: #999;

		image {
			width: 128rpx;
			height: 128rpx;
			margin-bottom: 16rpx;
		}
	}

	.main {
		padding-bottom: 190rpx;
		padding-top: 10rpx;
	}

	.workingFloat {
		width: 84px;
		background: #ffffff;
		border: 1px solid #eeeeee;
		border-radius: 100px 0px 0px 100px;
		box-shadow: 0px 1px 3px 0px rgba(126, 138, 146, 0.31);

		.content {
			display: flex;
			justify-content: space-around;
			align-items: center;
			padding: 20rpx 0;

			.word {
				font-size: 24rpx;
				color: #0091ff;
			}

			image {
				width: 32rpx;
				height: 32rpx;
				margin-left: 16rpx;
			}
		}

		.moreItem {
			font-size: 24rpx;
			color: #333;
			text-align: center;
			height: 34rpx;
			line-height: 34rpx;
			border-top: 1px solid #eee;
			padding: 20rpx 0;
		}
	}

	.offline-tips {
		color: #999999;
		font-size: 24rpx;
		text-align: center;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		padding-top: 20rpx;

		image {
			width: 32rpx;
			height: 32rpx;
		}
	}
}

.status-tabs {
	display: flex;
	// background-color: #fff;
	padding: 20rpx 20rpx;
	gap: 16rpx;
	// border-bottom: 1px solid #eee;
	// border-top: 1px solid #eee;

	.tab-item {
		padding: 8rpx 20rpx;
		border-radius: 2rem;
		font-size: 26rpx;
		color: #666;
		background-color: #fff;
		transition: .3s all;

		&.active {
			background-color: #DCF0FF;
			color: #0091FF;
		}
	}

	.sort-item {
		display: flex;
		align-items: center;
		font-size: 26rpx;
		color: #333;
		margin-left: auto;

		.icon {
			width: 32rpx;
			height: 32rpx;
		}
	}

	.sort-act {
		color: #0091FF;
	}
}
.more {
  width: 100%;
  padding: 30rpx 0;
  text-align: center;
  color: #999999;
  font-size: 24rpx;
}
</style>
